<?php

require_once('Adept/Binding/IMethod.php');

class Adept_Binding_Method extends Adept_ClassKit_Delegate implements Adept_Binding_IMethod 
{

    protected $objectId = '';
    protected $objectIndex = null;
    
    public function __construct($string = null) 
    {
        if ($string != null) {
            Adept_Binding_Parser::parseMethodBinding($string, $this);
        }
    }
    
    protected function findObject()
    {
        $context = Adept_Context::getInstance();        
        $object = $context->getAttribute($this->objectId);
        if (is_null($object)) {
        throw new Adept_Exception("Cannot find object with id: {$this->objectId} ");
        }
        
        if (!is_null($this->objectIndex)) {
            if (!isset($object[$this->objectIndex])) {
                throw new Adept_Exception("Cannot find index {$this->objectIndex} of id: {$this->objectId}");
            }
            $object = $object[$this->objectIndex];
        }    
        return $object;
    }    
    
    protected function invokeMethod($context, $args = array()) 
    {
        $this->setObject($this->findObject());
        return parent::invoke($args);
    }
    
    public function invoke($args) 
    {
        $context = Adept_Context::getInstance();
        return $this->invokeMethod($context, $args);
    }
    
    public function getObjectId() 
    {
        return $this->objectId;
    }
    
    public function setObjectId($objectId) 
    {
        $this->objectId = $objectId;
    }
    
    public function getObjectIndex() 
    {
        return $this->objectIndex;
    }
    
    public function setObjectIndex($objectIndex) 
    {
        $this->objectIndex = $objectIndex;
    }

}
